package com.chengqs.algorithm.recursionsingle;

public class E05InsertionSort {
    public static void sort(int[] arr) {
        insertion(arr, 1);
    }

    private static void insertion(int[] arr, int low) {
        if (low == arr.length) {
            return;
        }

        int t = arr[low];
        int i = low - 1; // 已排序区域指针
        while (i >= 0 && arr[i] > t) { // 没有找到插入位置
            arr[i + 1] = arr[i]; // 空出插入位置
            i--;
        }
        // 找到插入位置
        if (i + 1 != low) arr[i + 1] = t;

        insertion(arr, low + 1);
    }

    // 另一种插入排序的实现,缺点: 赋值次数较多
    private static void insertion2(int[] a, int low) {
        if (low == a.length) {
            return;
        }

        int i = low - 1;
        while (i >= 0 && a[i] > a[i + 1]) {
            int t = a[i];
            a[i] = a[i + 1];
            a[i + 1] = t;

            i--;
        }

        insertion(a, low + 1);
    }
}
